package com.eastfair.imaster.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.auth.api.AuthServiceFeign;
import com.eastfair.auth.entity.Organization;
import com.eastfair.auth.vo.ResourceOrganizationVo;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.excel.analyze.ExcelAnalyze;
import com.eastfair.core.excel.bean.ExcelAnalyzeExceptionResult;
import com.eastfair.core.excel.bean.ExcelAnalyzeResult;
import com.eastfair.imaster.dto.*;
import com.eastfair.imaster.entity.BusinessCircle;
import com.eastfair.imaster.entity.Company;
import com.eastfair.imaster.entity.Exhibitor;
import com.eastfair.imaster.service.CompanyService;
import com.eastfair.imaster.service.EmployeeService;
import com.eastfair.imaster.service.TccService;
import com.eastfair.imaster.vo.BusinessCircleVO;
import com.eastfair.imaster.vo.CompanyVo;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.echo.core.EchoService;
import com.eastfair.imaster.vo.EmployeeVo;
import com.eastfair.projectcore.vo.ProjectDbVo;
import com.eastfair.questionnaire.dto.QuestionnaireExcelDTO;
import com.eastfair.questionnaire.dto.QuestionnaireExcelResultDTO;
import com.eastfair.questionnaire.dto.QuestionnaireImportDTO;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import static com.eastfair.core.base.R.SUCCESS_CODE;
import static com.eastfair.core.exception.code.ExceptionCode.VISITOR_MOBILE_ERROR;


/**
 * <p>
 * 前端控制器
 * 公司表
 * </p>
 *
 * @author liuxiaobai
 * @date 2021-08-19
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/company")
@Api(value = "Company", tags = "公司表")
public class CompanyController extends SuperController<CompanyService, Long, Company, CompanyPageQuery, CompanySaveDTO, CompanyUpdateDTO> {

    @Autowired
    private EchoService echoService;

    @Autowired
    private AuthServiceFeign authServiceFeign;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private EmployeeService employeeService;
    @Override
    public void handlerResult(IPage<Company> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }

    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list) {
        List<Company> companyList = list.stream().map((map) -> {
            Company company = Company.builder().build();
            //TODO 请在这里完成转换
            return company;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(companyList));
    }


    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<CompanyPageQuery> params) {
        CompanyPageQuery companyPageQuery = params.getModel();
        //分页处理
        if (ContextUtil.getProjectId() != null) {
            companyPageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }


    /**
     * 添加公司
     *
     * @param companyDTO
     * @return
     */
    @ApiOperation(value = "添加公司", notes = "添加公司")
    @PostMapping("/executeCreateCompany")
    public R executeCreateCompany(@RequestBody @Validated({CompanyDTO.executeCreateCompany.class}) CompanyDTO companyDTO) {
        return baseService.executeCreateCompany(companyDTO, companyDTO.getAdminUserId());
    }

    /**
     * 修改公司
     *
     * @param companyDTO
     * @return
     */
    @ApiOperation(value = "修改公司", notes = "修改公司")
    @PutMapping("/executeUpdCompany")
    public R executeUpdCompany(@RequestBody @Validated({CompanyDTO.executeUpdCompany.class}) CompanyDTO companyDTO) {
        return baseService.executeUpdCompany(companyDTO);
    }

    /**
     * 审核公司是否通过认证
     *
     * @param companyDTO companyId 公司id  isCheck  true通过，false不通过
     * @return
     */
    @ApiOperation(value = "审核公司是否通过认证", notes = "审核公司是否通过认证")
    @PostMapping("/checkCompany")
    public R checkCompany(@RequestBody @Validated({CompanyDTO.checkCompany.class}) CompanyDTO companyDTO) {
        return baseService.checkCompany(companyDTO.getId(), companyDTO.getIsCheck() == 1 ? true : false);
    }

    /**
     * 查询公司以及下属员工
     *
     * @param companyId 公司id
     * @return
     */
    @ApiOperation(value = "查询公司以及下属员工", notes = "查询公司以及下属员工")
    @GetMapping("/queryCompany")
    public R<List<CompanyVo>> queryCompany(Long companyId) {
        CompanyDTO companyDTO = new CompanyDTO();
        companyDTO.setId(companyId);
        return R.success(baseService.queryCompany(companyDTO));
    }


    /**
     * 查询公司员工
     *
     * @param companyId 公司id
     * @return
     */
    @ApiOperation(value = "查询公司员工", notes = "查询公司员工")
    @GetMapping("/queryEmployee")
    public R<List<EmployeeVo>> queryEmployee(Long companyId) {
        EmployeeDTO employeeDTO = new EmployeeDTO();
        employeeDTO.setCompanyId(companyId);
        return R.success(employeeService.queryEmployeeOfCompany(employeeDTO));
    }



    /**
     * 批量查询公司信息
     *
     * @param companyDTO ids 公司id集合
     * @return
     */
    @ApiOperation(value = "批量查询公司信息", notes = "批量查询公司信息")
    @GetMapping("/queryByIds")
    public R<List<CompanyVo>> queryByIds(CompanyDTO companyDTO) {
        return R.success(ConvertUtil.convertList(baseService.list(null, companyDTO.getIds()), CompanyVo.class));
    }

    /**
     * 查询公司信息
     *
     * @return
     */
    @ApiOperation(value = "查询公司信息", notes = "查询公司信息")
    @GetMapping("/findById")
    public R<CompanyVo> findById(@RequestParam(value = "id") Long id) {
        List<Company> companyList = baseService.list(null, Arrays.asList(id));
        if (companyList != null && !companyList.isEmpty()) {
            CompanyVo companyVo = new CompanyVo();
            BeanUtils.copyProperties(companyList.get(0), companyVo);
            return R.success(companyVo);
        }
        return null;
    }


    /**
     * 查询单个公司
     *
     * @param id 主键id
     * @return
     */
    @GetMapping("/getAndRoleById/{id}")
    public R<CompanyVo> getAndRoleById(@PathVariable(value = "id") Long id) {
        return R.success(baseService.getAndRoleById(id));
    }


    /**
     * 分页查询
     *
     * @param params 参数
     * @return 分页数据
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @PostMapping("/queryPage")
    public R<Page<CompanyVo>> queryPage(@RequestBody PageParams<CompanyDTO> params) {
        return this.baseService.queryPage(params);
    }

    /**
     * 删除
     *
     * @param companyIds 公司id集合
     * @return
     */
    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping("/del")
    public R del(@RequestBody List<Long> companyIds) {
        return R.success(baseService.delCompany(companyIds));
    }


    /**
     * tcc 测试
     *
     * @param id 主键id
     * @return
     */
    @GetMapping("/test/{id}")
    public R test(@PathVariable(value = "id") Long id) {
        GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate();
//        return tccService.executeTest(id);
        return companyService.executeTcc(id);
    }

}
